<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="入库人姓名" prop="returnerName">
        <el-input
          v-model="queryParams.returnerName"
          placeholder="请输入入库人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="负责人姓名" prop="responsibleUserName">
        <el-input
          v-model="queryParams.responsibleUserName"
          placeholder="请输入负责人姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


<!--      <el-form-item label="仓库名称" prop="warehouseName">-->
<!--        <el-select v-model="queryParams.warehouseName" placeholder="请输入仓库名称">-->
<!--          <el-option-->
<!--            v-for="item in warehouseList"-->
<!--            :key="item.id"-->
<!--            :label="item.warehouseName"-->
<!--            :value="item.warehouseName">-->
<!--          </el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item label="入库时间" prop="returnTime">
        <el-date-picker clearable
          v-model="queryParams.returnTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择入库时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['module:receipt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['module:receipt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:receipt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['module:receipt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table :border="true" v-loading="loading" :data="receiptList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" width="55" align="center" label="序号" />
      <el-table-column label="入库人姓名" align="center" prop="returnerName" v-if="columns[0].visible"/>
      <el-table-column label="负责人姓名" align="center" prop="responsibleUserName" v-if="columns[1].visible"/>
      <el-table-column label="入库类型" align="center" prop="returnType" v-if="columns[3].visible"/>
      <el-table-column label="入库时间" align="center" prop="createTime" width="180" v-if="columns[4].visible"/>
<!--      <el-table-column label="入库时间" align="center" prop="returnTime" width="180" v-if="columns[4].visible">-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.returnTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="入库详情" align="center"   v-if="columns[2].visible">
        <template slot-scope="scope">
          <el-button type="primary" @click="details(scope.row)">入库详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[5].visible"/>
      <el-table-column label="状态" fixed="right" align="center" prop="status" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status==0">归还入库</el-tag>
          <el-tag v-if="scope.row.status==1">采购入库申请中</el-tag>
          <el-tag v-if="scope.row.status==2">已同意采购入库</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlePutExport(scope.row)"
            v-if="scope.row.status !=2"
          >同意入库</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['module:receipt:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['module:receipt:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
<!--        <el-form-item label="入库人id" prop="returnerId">-->
<!--          <el-input v-model="form.returnerId" placeholder="请输入入库人id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="负责人id" prop="responsibleUser">-->
<!--          <el-input v-model="form.responsibleUser" placeholder="请输入负责人id" />-->
<!--        </el-form-item>-->
        <el-form-item label="入库人姓名" prop="returnerName">
          <el-input disabled="true" style="width: 200px;" v-model="form.returnerName" placeholder="请输入入库人姓名" >
            <el-button slot="append" icon="el-icon-user" @click="handleStaff(0)" ></el-button>
          </el-input>
        </el-form-item>


        <el-form-item label="负责人姓名" prop="responsibleUserName">
          <el-input  disabled="true"style="width: 200px;" v-model="form.responsibleUserName" placeholder="请输入负责人姓名" >
            <el-button slot="append" icon="el-icon-user" @click="handleStaff(1)" ></el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="入库类型" prop="returnType">
          <el-input disabled="true"  style="width: 200px;" v-model="form.returnTypeName" placeholder="请输入负责人姓名" />
<!--          <el-select style="width: 200px;" v-model="form.returnType" @change="changeType" placeholder="请选择仓库名称">-->
<!--            <el-option-->
<!--              v-for="item in returnTypeList"-->
<!--              :key="item.id"-->
<!--              :label="item.dictLabel"-->
<!--              :value="item.dictValue">-->
<!--            </el-option>-->
<!--          </el-select>-->
        </el-form-item>
        <el-table v-if="form.returnType==2"   :border="true" :data="bizReceiptProductList" style="margin-bottom: 10px;" >
          <el-table-column type="index" width="55" align="center"  />
          <el-table-column label="产品名称" align="center" prop="productName"  />
          <el-table-column label="产品类型" align="center" prop="productType" />
          <el-table-column  label="总数量" align="center" prop="numbers" />
          <el-table-column  label="单价" align="center" prop="price" />
        </el-table>
        <el-form-item v-if="form.returnType" label="入库物品" prop="bizOutboundProduct">
          <el-button type="primary"  @click="handleProduct" v-if="form.returnType==1">归还产品</el-button>
          <el-button type="primary" @click="addProduct" v-if="form.returnType==2 " >新增产品</el-button>
        </el-form-item>
        <el-table v-if="form.returnType" :border="true" :data="form.bizReceiptProductList" style="margin-bottom: 10px;" >
          <el-table-column type="index" width="55" align="center"  />
          <el-table-column label="产品名称" align="center" prop="productName"  />
           <el-table-column label="产品类型" align="center" prop="productType" />
          <el-table-column label="产品仓库" align="center" prop="warehouseName"  width="200px"  >
            <template slot-scope="scope">
              <el-input v-model="scope.row.warehouseName" placeholder="请选择仓库"  style="width: 150px;">
                <el-button slot="append" icon="el-icon-search" @click="selectWarehouse(scope)" style="width: 50px"></el-button>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column v-if="form.returnType==1" label="总数量" align="center" prop="quantity" />
          <el-table-column v-if="form.returnType==1" label="归还数量" align="center" prop="number" >
              <template slot-scope="scope">
                <el-input v-model="scope.row.number" placeholder="归还数量"  style="width: 80px;"></el-input>
              </template>
            </el-table-column>
            <el-table-column v-if="form.returnType==2" label="单价" align="center" prop="price" />
          <el-table-column v-if="form.returnType==2" label="新增入库数量" align="center" prop="number"  >
            <template slot-scope="scope">
              <el-input v-model="scope.row.number" @change="focusBtn(scope)" placeholder="新增入库数量"  style="width: 80px;"></el-input>
            </template>
          </el-table-column>
            <el-table-column v-if="form.id == null" label="操作" align="center"  >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="deleteBtn(scope)"
                >删除</el-button>
              </template>
            </el-table-column>
        </el-table>


        <el-form-item label="入库时间" prop="returnTime">
          <el-date-picker clearable
                          style="width: 200px;"
            v-model="form.returnTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择入库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item style="width: 200px;" label="备注" prop="remark">
          <el-input style="width: 200px;" type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <importUser ref="importCustomer" @showUser="showCustomer"></importUser>
    <importProduct ref="importProduct" @showProduct="showProduct"></importProduct>
    <importAddProduct ref="importAddProduct" @showAddProduct="showAddProduct"></importAddProduct>
    <importEnterpriseProduct ref="importEnterpriseProduct" @showEnterprise="showEnterprise" :stockList="bizReceiptProductList"></importEnterpriseProduct>
    <importWarehouse ref="importWarehouse" @showWarehouse="showWarehouse"></importWarehouse>
    <!-- 入库详情   -->
    <el-dialog title="入库详情" :visible.sync="receiptOpen" width="50%" append-to-body>
      <el-table :border="true"  :data="detailsList" >
        <el-table-column label="产品名称" align="center" prop="productName"  />
        <el-table-column label="产品类型" align="center" prop="productType"  />
        <el-table-column label="价格" align="center" prop="price" >
          <template slot-scope="scope">
            <div >{{scope.row.price}}</div>
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center" prop="number"  />
        <el-table-column label="仓库" align="center" prop="warehouseName"  />
      </el-table>
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary"  >确 定</el-button>-->
<!--        <el-button>取 消</el-button>-->
<!--      </div>-->

    </el-dialog>

  </div>
</template>

<script>
import { putReceipt,listReceipt, getReceipt, delReceipt, addReceipt, updateReceipt } from "@/api/module/receipt";
import {listWarehouse} from "@/api/module/warehouse";
import  importUser from '@/views/module/common/user'
import {getDicts} from '@/api/system/dict/data.js'
import  importProduct from '@/views/module/outbound/product'
import  importAddProduct from '@/views/module/outbound/addProduct'
import importEnterpriseProduct from '@/views/module/receipt/enterpriseProduct'
import importWarehouse from '@/views/module/receipt/warehouse'


export default {
  name: "Receipt",
  components:{
    importUser,
    importProduct,
    importAddProduct,
    importEnterpriseProduct,
    importWarehouse
  },
  data() {
    return {
      price:0,
      priceNum:0,
      index:'',
      priceShow:false,
      receiptOpen:false,
      detailsList:[],
      type:'',//入库人负责人
      warehouseList:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 入库记录表格数据
      receiptList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        returnerId: null,
        returnerName: null,
        responsibleUser: null,
        responsibleUserName: null,
        warehouseId: null,
        warehouseName: null,
        returnType: null,
        returnTime: null,
      },
      returnTypeList:[],//入库类型
      // 表单参数
      form: {
        returnType:'1',
        returnerName:'',
        responsibleUserName:'',
        bizReceiptProductList:[{number:"12"}]

      },
      columns: [
        { key: 0, label: `入库人名`, visible: true },
        { key: 1, label: `负责人名`, visible: true },
        { key: 2, label: `入库详情`, visible: true },
        { key: 3, label: `入库类型`, visible: true },
        { key: 4, label: `入库时间`, visible: true },
        { key: 5, label: `备注`, visible: true },


      ],
      // 表单校验
      rules: {
        returnerName: [
          { required: true, message: '请输入入库人', trigger: 'blur' },
        ],
        responsibleUserName: [
          { required: true, message: '请输入负责人', trigger: 'blur' },
        ],
        warehouseName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
        ],
        returnTime: [
          { required: true, message: '请输入入库时间', trigger: 'blur' },
        ],
        returnType: [
          { required: true, message: '请选择入库类型', trigger: 'blur，change' },
        ],
      },
      bizReceiptProductList:[],
    };
  },
  created() {
    this.getReturnType()

    this.WarehouseList()
    this.getList();
  },
  methods: {
    showWarehouse(value){
      console.log(value)
      var tem={...value}
      let index=this.index
      console.log(this.index)
      this.form.bizReceiptProductList[index].warehouseId=tem.id
      this.form.bizReceiptProductList[index].warehouseName=tem.warehouseName
      console.log(this.form.bizReceiptProductList[index])

    },
    /** 选择仓库*/
    selectWarehouse(value){
      console.log(value)
      this.index=value.$index
      this.$refs.importWarehouse.show()
    },
    // 新增form.bizReceiptProductList
    showEnterprise(value){
      console.log(value)
      value.number=''
      var tem={...value}
      this.form.bizReceiptProductList.push(tem)

      console.log(this.form.bizReceiptProductList)
    },
    focusBtn(value){
      let price=0
      let priceNum=0
      this.form.bizReceiptProductList.forEach(item=>{
        price=Number(price)+Number(item.number)
      })
      this.bizReceiptProductList.forEach(item=>{
        priceNum=Number(priceNum)+Number(item.numbers)
      })
      console.log(price)
      console.log(priceNum)
      this.price=price
      this.priceNum=priceNum
      if(price>priceNum){
        this.$message('当前数量大于需要输入的总量')
      }else if(price==priceNum){
        this.$message('刚好')
      }
    },
    /** 同意入库 点击 弹出弹框*/
    handlePutExport(value){
      console.log(value)
      this.form.returnType=2
      this.form.returnTypeName='入库'
      this.form.id=value.id
      this.bizReceiptProductList=value.bizReceiptProductList
      this.bizReceiptProductList.forEach(item=>{
        item.name=item.productName
        item.numbers=item.number
      })

      this.form.bizReceiptProductList=[]
      this.open=true

    },
    details(value){
      console.log(value)
      this.detailsList=value.bizReceiptProductList
      this.receiptOpen=true
    },
    deleteBtn(value){
      this.form.bizReceiptProductList.splice(value.$index,1)
    },
    /** 切换入库类型 table清空 */
    changeType(){
      this.form.bizReceiptProductList=[]
    },
    /** 选择新增入库*/
    addProduct(){

      this.$refs.importEnterpriseProduct.show()
    },
    showAddProduct(value){
      console.log(value)
      console.log(this.form.bizReceiptProductList)
      this.form.bizReceiptProductList.push(value)
      console.log(this.form.bizReceiptProductList)


    },
    /** 选择归还入库*/
    handleProduct(){
      this.$refs.importProduct.show()
    },
    showProduct(val){
      console.log(val)
      this.form.bizReceiptProductList=val
      // console.log( this.bizReceiptProductList)
    },
    /** 选择人员*/
    handleStaff(value){
      console.log(value)
      this.type=value
      this.$refs.importCustomer.show();
    },
    showCustomer(value){
      if(this.type==0){
        /** 领用人*/
        this.form.returnerId=value.userId
        this.form.returnerName=value.userName
      }else if(this.type==1){
        /** 负责人*/
        this.form.responsibleUser=value.userId
        this.form.responsibleUserName=value.userName
      }
    },
    /** 采购入库类型 return_type*/
    getReturnType(){
      getDicts('return_type').then(response=>{
        // console.log(response)
        this.returnTypeList=response.data
      })
    },
    getValue(arr, item) {
      for (let i = 0; i < arr.length; i++) {
        if (item === arr[i].dictValue) {
          return arr[i].dictLabel
        }
      }
    },

    /** 查询仓库管理列表 */
    WarehouseList() {
      this.loading = true;
      listWarehouse(this.queryParams).then(response => {
        this.warehouseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询入库记录列表 */
    getList() {
      this.loading = true;
      listReceipt(this.queryParams).then(response => {
        response.rows.forEach(item=>{
          item.returnType=this.getValue(this.returnTypeList,item.returnType)
        })
        console.log(response.rows)
        this.receiptList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        returnerId: null,
        returnerName: null,
        responsibleUser: null,
        responsibleUserName: null,
        warehouseId: null,
        warehouseName: null,
        returnType: null,
        returnTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        remark: null,
        bizReceiptProductList:[]
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.returnType=1
      this.form.returnTypeName='归还'
      this.open = true;
      this.title = "添加入库记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getReceipt(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改入库记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form)
      console.log(this.form.id)
      if(this.form.returnType=='2'){

        // let price=0
        // let priceNum=0
        // this.form.bizReceiptProductList.forEach(item=>{
        //   price=Number(price)+Number(item.number)
        // })
        // this.bizReceiptProductList.forEach(item=>{
        //   priceNum=Number(priceNum)+Number(item.numbers)
        // })
        // console.log(price)
        // console.log(priceNum)
        if(this.price==this.priceNum){
          console.log(this.form.id)

          delReceipt(this.form.id)
          // this.$message('12')
        }
        this.form.id=null
        this.form.status='2'
        console.log(this.form.id)

      }
      console.log(this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateReceipt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReceipt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库记录编号为"' + ids + '"的数据项？').then(function() {
        return delReceipt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('module/receipt/export', {
        ...this.queryParams
      }, `receipt_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
